package com.yu.newsSys.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

// 数据库工具类型
public class JDBCUtils_bak {

    // 驱动
    private static String driver;
    // url
    private static String url;
    // 账户
    private static String user;
    // 密码
    private static String pass;

    // 初始化静态资源
    static {
        // 1.定义输入流
        InputStream is = null;

        try {
            /*
                类加载器方式读取配置文件，需要保证的是该properties文件位于类路径下(com/yu/newsSys/utils/JDBCUtils.java)
            */

            is = JDBCUtils_bak.class.getClassLoader().getResourceAsStream("db.properties");
            // 3.读取配置文件
            Properties properties = new Properties();
            properties.load(is);

            // 4.初始化参数
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            pass = properties.getProperty("pass");

            // 5.加载驱动
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 获取数据库连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, pass);
    }

    // 关闭资源
    public static void close(ResultSet rs, Statement sta, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (sta != null) {
            try {
                sta.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
